package com.jxgm.spring.boot.controller;

import com.jxgm.spring.boot.entity.Department;
import com.jxgm.spring.boot.service.DepartmentService;
import com.jxgm.spring.boot.service.EmpService;
import com.jxgm.spring.boot.entity.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;


import java.util.Collection;

/**
 * @author Administrator
 * @date 2020/10/14 9:24
 * @description
 **/
@Controller
public class EmpController {

    @Autowired
    private EmpService empService;

    @Autowired
    private DepartmentService departmentService;

    @GetMapping(value = "/emps")
    public String list(ModelMap modelMap){

        Collection<Emp> emps = empService.getEmps();
        modelMap.addAttribute("emps",emps);
        return "emps/list";
    }

    @GetMapping(value = "/emp")
    public String toAddPage(ModelMap modelMap){
        Collection<Department> departments = departmentService.getDepartments();
        modelMap.addAttribute("depts",departments);
        return "emps/add";
    }

    @PostMapping(value = "/emp")
    public String addEmp(Emp emp){

        empService.saveEmp(emp);

        return "redirect:/emps";
    }

    @GetMapping(value = "/emp/{empId}")
    public String toEditPage(@PathVariable("empId") Integer empId,ModelMap modelMap){

        Emp emp = empService.getId(empId);
        modelMap.addAttribute("emp",emp);
        Collection<Department> departments = departmentService.getDepartments();
        modelMap.addAttribute("depts",departments);
        return "emps/add";

    }

    @PutMapping(value = "/emp")
    public String updateEmp(Emp emp,ModelMap modelMap){

        empService.saveEmp(emp);

        return "redirect:/emps";
    }


    @DeleteMapping(value = "/emp/{empId}")
    public String deleteEmp(@PathVariable("empId") Integer empId){

        empService.removeId(empId);

        return "redirect:/emps";

    }

}
